﻿var Product = {
    version: '1.0.0.0.0',
    ProductType: 1,
    PageIndex: 1,
    PageSize: 20,
    NotActive: 1,
    Active: 2,

    Init: function () {
        $('form').jqTransform();

        Product.DropDownListCategory("#ddlCategory", 0);
        Product.ListSearch(Product.PageIndex);

        $("#txtKeyword").keypress(function (event) {
            if (event.which == 13) {
                Product.ListSearch(Product.PageIndex);
                event.preventDefault();
            }
        });
    },

    ListSearch: function (pageIndex) {
        $('#toTop').click();

        var keyword = $('#txtKeyword').val();

        var categoryId = 0;
        $.each($('#ddlCategory ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlCategory select.jqTransformHidden option:eq(' + index + ')').attr('value');
                if (value > 0 && value != undefined)
                    categoryId = value;
            }
        });

        var status = 0;
        $.each($('#ddlStatus ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlStatus select.jqTransformHidden option:eq(' + index + ')').attr('value');
                status = value;
            }
        });

        var orderBy;
        $.each($('#ddlOrderBy ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlOrderBy select.jqTransformHidden option:eq(' + index + ')').attr('value');
                orderBy = value;
            }
        });

        var pageSize = Product.PageSize;
        $.each($('#ddlPageSize ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlPageSize select.jqTransformHidden option:eq(' + index + ')').attr('value');
                pageSize = value;
            }
        });

        var url = String.format('/GetRequest.ashx?m=product&action=search&keyword={0}&cId={1}&status={2}&orderBy={3}&pi={4}&ps={5}&rand={6}',
                    keyword, categoryId, status, orderBy, pageIndex, pageSize, Math.random());

        $.getJSON(url, function (res) {
            if (res != null) {
                $('.pages').html(res.Pager);

                $.Mustache.load('/templates/product/list.htm')
                    .done(function () {
                        $('#listProduct tbody').html('');
                        $('#listProduct tbody').mustache('tpl-product-list', res);
                        $('.topDir').tipsy({ fade: true, gravity: 's' });
                        $('form').jqTransform();
                    });
            }
        });
    },

    ListByCategory: function () {
        var categoryId = 0;
        $.each($('#ddlCategory ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlCategory select.jqTransformHidden option:eq(' + index + ')').attr('value');
                if (value > 0 && value != undefined)
                    categoryId = value;
            }
        });

        if (categoryId > 0) {
            var url = String.format('/GetRequest.ashx?m=product&action=getproductbycategory&cId={0}&rand={1}', categoryId, Math.random());
            $.getJSON(url, function (res) {
                if (res.Success) {
                    var html = '';                
                    for (var i = 0; i < res.Data.length; i++) {
                        html += String.format('<option value="0">{1}</option>', res.Data[i]["ProductId"], res.Data[i]["Code & Name"]);
                    }
                    
                    $('#box1View').html(html);
                }                
            });
        }
    },

    DropDownListCategory: function (ddlArea, selected) {
        var url = String.format('/GetRequest.ashx?m=category&action=listtree&tId={0}&rand={1}', Product.ProductType, Math.random());
        $.getJSON(url, function (res) {
            if (res.Success) {
                if (res != null) {
                    var html = '';
                    html += '<select style="width: 160px" onchange="Product.ListSearch(Product.PageIndex);">';

                    if (res.Data.length > 0) {
                        html += '<option value="0">-- Tất cả --</option>';

                        $.each(res.Data, function (i, val) {
                            if (selected > 0 && val.CategoryId == selected)
                                html += String.format('<option value="{0}" selected="selected">{1}</option>', val.CategoryId, val.Name);
                            else
                                html += String.format('<option value="{0}">{1}</option>', val.CategoryId, val.Name);
                        });
                    }
                    else {
                        html += '<option value="0">-- Gốc --</option>';
                    }

                    html += '</select>';

                    $(ddlArea).html(html);
                    $('form').jqTransform();
                }
            }
        });
    },

    DropDownListBuySellCategory: function (ddlArea, selected) {
        var url = String.format('/GetRequest.ashx?m=category&action=listtree&tId={0}&rand={1}', Product.ProductType, Math.random());
        $.getJSON(url, function (res) {
            if (res.Success) {
                if (res != null) {
                    var html = '';
                    html += '<select style="width: 300px" onchange="Product.ListByCategory();">';

                    if (res.Data.length > 0) {
                        $.each(res.Data, function (i, val) {
                            if (selected > 0 && val.CategoryId == selected)
                                html += String.format('<option value="{0}" selected="selected">{1}</option>', val.CategoryId, val.Name);
                            else
                                html += String.format('<option value="{0}">{1}</option>', val.CategoryId, val.Name);
                        });
                    }

                    html += '</select>';

                    $(ddlArea).html(html);
                    $('form').jqTransform();

                    // Fix Height Dropdown List
                    var tempStyle = $('.jqTransformSelectWrapper').find('ul').attr('style');
                    tempStyle = tempStyle.replace('height: 0px;', '');
                    $('.jqTransformSelectWrapper').find('ul').attr('style', tempStyle);
                }
            }
        });
    },

    DropDownListExcelCategory: function (ddlArea, selected) {
        var url = String.format('/GetRequest.ashx?m=category&action=listtree&tId={0}&rand={1}', Product.ProductType, Math.random());
        $.getJSON(url, function (res) {
            if (res.Success) {
                if (res != null) {
                    var html = '';
                    html += '<select style="width: 200px">';

                    if (res.Data.length > 0) {
                        html += '<option value="0">-- Tất cả --</option>';

                        $.each(res.Data, function (i, val) {
                            if (selected > 0 && val.CategoryId == selected)
                                html += String.format('<option value="{0}" selected="selected">{1}</option>', val.CategoryId, val.Name);
                            else
                                html += String.format('<option value="{0}">{1}</option>', val.CategoryId, val.Name);
                        });
                    }
                    else {
                        html += '<option value="0">-- Gốc --</option>';
                    }

                    html += '</select>';

                    $(ddlArea).html(html);
                    $('form').jqTransform();
                }
            }
        });
    },

    ChangeStatus: function (status) {
        var count = 0;
        $.each($('#grdList tbody tr'), function () {
            var isSelected = $(this).find('td:eq(0) a');
            if ($(isSelected).hasClass('jqTransformChecked') == true) {
                count++;
                var productId = ($(this).find('td:eq(0) input').attr('value'));

                var url = String.format('/GetRequest.ashx?m=product&action=changestatus&pId={0}&status={1}', productId, status);
                $.post(url, function () { })
                    .done(function () {
                        Product.ListSearch(Product.PageIndex);
                    });
            }
        });

        if (count == 0)
            $.jGrowl(String.format('Bạn cần chọn sản phẩm để cập nhật <br/> trạng thái.'), { header: 'Cảnh báo:' });
        else
            $.jGrowl(String.format('Cập nhật trạng thái sản phẩm thành công!'), { header: 'Thông báo:' });
    },

    ReadExcel: function () {
        var propertyType = 0;
        $.each($('#ddlPropertyType ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlPropertyType select.jqTransformHidden option:eq(' + index + ')').attr('value');
                propertyType = value;
            }
        });

        var categoryId = 0;
        $.each($('#ddlCategory ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlCategory select.jqTransformHidden option:eq(' + index + ')').attr('value');
                if (value > 0 && value != undefined)
                    categoryId = value;
            }
        });

        var status = 0;
        $.each($('#ddlStatus ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlStatus select.jqTransformHidden option:eq(' + index + ')').attr('value');
                status = value;
            }
        });

        var filePath = $('#txtFilePath').val();
        var url = String.format('/GetRequest.ashx?m=product&action=readexcel&tId={0}&status={1}&cId={2}&filePath={3}', propertyType, status, categoryId, filePath);

        $.ajax({
            type: "POST",
            url: url,
            dataType: 'json'
        }).done(function (res) {

            $('#excelArea').css('display', 'block');

            if (res.Success) {
                $.Mustache.load('/templates/excel/product.htm')
                    .done(function () {
                        $('#lstProduct_ProperyValue tbody').html('');
                        $('#lstProduct_ProperyValue tbody').mustache('tpl-excel-product-list', res);
                        $('#btnSave').css('display', 'block');
                    });
            }
            else {
                $('#lstProduct_ProperyValue tbody').html(res.Message);
            }
        });
    },

    ExecuteExcel: function () {
        var propertyType = 0;
        $.each($('#ddlPropertyType ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlPropertyType select.jqTransformHidden option:eq(' + index + ')').attr('value');
                propertyType = value;
            }
        });

        var categoryId = 0;
        $.each($('#ddlCategory ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlCategory select.jqTransformHidden option:eq(' + index + ')').attr('value');
                if (value > 0 && value != undefined)
                    categoryId = value;
            }
        });

        var status = 0;
        $.each($('#ddlStatus ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlStatus select.jqTransformHidden option:eq(' + index + ')').attr('value');
                status = value;
            }
        });

        var filePath = $('#txtFilePath').val();
        var url = String.format('/GetRequest.ashx?m=product&action=executeexcel&tId={0}&status={1}&cId={2}&filePath={3}', propertyType, status, categoryId, filePath);

        $.ajax({
            type: "POST",
            url: url,
            dataType: 'json',
            timeout: 3600
        }).done(function (res) {
            var html = '';

            if (res.Success) {
                html += '<div class="nNote nSuccess hideit">';
                html += String.format('<p><strong>Thành công: </strong>{0}</p>', res.Message);
                html += '</div>';
                $('#excelArea').css('display', 'none');
                $('#message').html(html);
            }
            else {
                html += '<div class="nNote nFailure hideit">';
                html += String.format('<p><strong>Lỗi: </strong>{0}</p>', res.Message);
                html += '</div>';
                $('#excelArea').css('display', 'none');
                $('#message').html(html);
            }
        });
    },

    ExportExcel: function () {
        var sizeType = 0;
        $.each($('#ddlSizeType ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlSizeType select.jqTransformHidden option:eq(' + index + ')').attr('value');
                sizeType = value;
            }
        });

        var categoryId = 0;
        $.each($('#ddlCategory ul li a'), function () {
            if ($(this).attr('class') == 'selected') {
                var index = $(this).attr('index');
                var value = $('#ddlCategory select.jqTransformHidden option:eq(' + index + ')').attr('value');
                if (value > 0 && value != undefined)
                    categoryId = value;
            }
        });

        $('#urlExcel').css('display', 'block');
        $('#urlExcel .formRight').html(String.format('<a href="/handler/GetExcel.ashx?tId={0}&cId={1}" style="line-height: 26px; font-weight: bold">Tải về mẫu excel</a>', sizeType, categoryId));
    },

    ReadImportExport: function () {

    },

    ExecuteImportExport: function () {

    },

    Delete: function (id) {
        $('#listProduct table tr').removeClass('gradeC');
        $('#p-' + id).addClass('gradeC');

        jConfirm('', 'Bạn có chắc chắn muốn xóa?', function (result) {
            if (result) {
                var url = String.format('/GetRequest.ashx?m=product&action=delete&pId={0}', id);
                $.ajax({
                    type: "POST",
                    url: url,
                    dataType: 'json'
                }).done(function (res) {
                    if (res.Success) {
                        Product.ListSearch(Product.PageIndex);
                        $.jGrowl(String.format('Xóa sản phẩm thành công!'), { header: 'Thông báo:' });
                    }
                    else {
                        $.jGrowl(String.format('Bạn cần xóa các thông tin liên quan của sản phẩm!'), { header: 'Thông báo:' });
                    }
                });
            }
        });
    }
};